package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.mapper.DishMapper;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Slf4j
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {
    @Autowired
    private DishFlavorService dishFlavorService;

    @Override
    public void updateWithFlavor(DishDto dishDto) {
        //更改dish基本信息
        this.updateById(dishDto);
        //根据菜品id先删除dish_flavor表中对应的口味信息
        LambdaQueryWrapper<DishFlavor> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DishFlavor::getDishId,dishDto.getId());
        dishFlavorService.remove(wrapper);

        //获取dishDto的所有口味
        List<DishFlavor> flavorList = dishDto.getFlavors();
        //遍历循环所有口味
        for (DishFlavor dishFlavor : flavorList) {
            //将口味id赋值给菜品id
            dishFlavor.setDishId(dishDto.getId());
        }
        //批量保存口味到菜品口味表
        dishFlavorService.saveBatch(flavorList);
    }

    /**
     * 根据id查询菜品信息包含口味
     * @param id
     * @return
     */
    @Override
    public DishDto getByIdWithFlavor(Long id) {
        //查询菜品的基本信息
        Dish dish = this.getById(id);
        //创建dishDto对象
        DishDto dishDto = new DishDto();
        //拷贝数据
        BeanUtils.copyProperties(dish,dishDto);
        //查看当前菜品的口味信息，从dish_flavor查询
        LambdaQueryWrapper<DishFlavor> wrapper = new LambdaQueryWrapper<>();
        //比较dish的id是否与dish_flavor的id值相同相同
        wrapper.eq(DishFlavor::getDishId,dish.getId());
        //调用service层方法List
        List<DishFlavor> list = dishFlavorService.list(wrapper);
        //给dishDto赋值口味
        dishDto.setFlavors(list);
        //返回信息
        return dishDto;
    }
    /**
     * 保存新的菜品和口味
     * @param dishDto
     */
    @Override
    @Transactional
    public void saveWithFlavor(DishDto dishDto) {
        //保存基本信息到菜品表dish
        save(dishDto);
        //获取新增菜品的id
        Long id = dishDto.getId();
        //获取所有菜品口味
        List<DishFlavor> flavors = dishDto.getFlavors();
        for (DishFlavor flavor : flavors) {
            flavor.setDishId(id);
        }
        //批量保存菜品口味到菜品口味表
        dishFlavorService.saveBatch(flavors);
    }


}
